import { defineStore } from "pinia";
import { ref } from "vue";
import { STORAGE_TOKEN_KEY } from "./mutation-type";
import { PageEnum } from "@/enums/pageEnum";
import { AdminUserApi, AdminUserLoginModel, MyApi } from "@/api";

export const useAuthStore = defineStore("auth", () => {
  let userJson = localStorage.getItem("userInfo");
  
  const token = ref(localStorage.getItem(STORAGE_TOKEN_KEY) || "");
  const userInfo = ref(userJson ? JSON.parse(userJson) : {});
  const isAuthenticated = ref(!!token.value);

  const login = async (params: AdminUserLoginModel) => {
    await AdminUserApi.adminuserLogin(params);

    token.value = localStorage.getItem(STORAGE_TOKEN_KEY) || "";
    isAuthenticated.value = !!token.value;

    if (token.value) {
      getUserInfo();
    }
  };

  const logout = async () => {
    await AdminUserApi.adminuserLogout();
    token.value = "";
    userInfo.value = null;
    localStorage.removeItem(STORAGE_TOKEN_KEY);
    localStorage.removeItem("userInfo");
    // 强制刷新清除所有缓存
    window.location.href = PageEnum.BASE_LOGIN; // 用原生跳转避免路由缓存
  };

  const getUserInfo = async () => {
    let res = await MyApi.myGetuserinfo();
    userInfo.value = {
      userName: res.name || "林老师",
      avatar: "/resource/images/header.jpg",
      userId: res.id,
      mobile: res.mobile || null,
    };

    // 持久化存储
    localStorage.setItem("userInfo", JSON.stringify(userInfo.value));
  };

  return { token, userInfo, isAuthenticated, login, logout, getUserInfo };
});
